
// 用户积分设置： 文章加精积分+20， 被收藏或者被点赞积分+2
function factory (ArticleModel, UserModel) {

  var updateArticleRoutes = {
   
    //  评论
    comment: function (req, res) {
      var body = req.body
      ArticleModel.findOne({_id: body.articleId}, function (err, article) {
        article.comment.push(body.comment)
        article.save(function(err, article) {
          res.send('1')
        })
      })
    },
    read: function (req, res) {
      ArticleModel.findOne({_id: req.body.articleId}, function (err, art) {
        art.read++
        art.save(function (err, art) {
          res.send('1')
        })
      })
    }
  }
  
  var keys = ['good', 'bad', 'collected']
  keys.map(function (key, index) {
    //  阅读、好评、差评、收藏 + 1 的动作，除了阅读，其他都存储用户id
    updateArticleRoutes[key] = function (req, res) {
      ArticleModel.findOne({_id: req.body.articleId}, function (err, art) {
        var status = art.status['user_set_' + key]
        if (status.indexOf(req.body.handlerId) > -1) {
          res.send('0')
        }else {
          art[key]++
          status.push(req.body.handlerId)
          art.save(function (err, art) {
            UserModel.findOne({user: art.autor}, function (err, user) {
              if (key !== 'bad') {
                user.integral += 2
              }
              if (key === 'collected') {
                user.collect.push(req.body.articleId)
              }
              user.save(function (err, user) {
                res.send('1')
              })
              
            })
          })
        }
        
      })
    }
  })

  return updateArticleRoutes
}

module.exports = factory